/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useEffect, useRef, useState } from 'react';
import ProForm, {
  DrawerForm,
  ProFormSelect,
  ProFormDependency,
  ProFormCheckbox,
  ProFormDigit,
} from '@ant-design/pro-form';
import type { ProFormInstance } from '@ant-design/pro-form';
import type { Shunfen } from '../../..';
import { setShunFun, resetShunFun } from '@/services/jdk/register';
import { getBrandList } from '@/services/jdk/shield';
import { Space, message, Popconfirm } from 'antd';
import { mode_name, layoutCol } from '../../../utils/index.config';
import type { OptionsType } from '@/components/_pages/jdk/addLeague/_utils/type';

interface KbSfDrawerProps {
  queryData: { user_id?: string; league_id?: string; type: 'league' | 'merchant' };
  record: Shunfen;
  onComplete: Function;
  winSize: string | undefined;
}
const KbSfDrawer = ({ queryData, record, onComplete, winSize }: KbSfDrawerProps) => {
  const roleName = queryData.type === 'league' ? '加盟商' : '商家';
  const [visible, setVisible] = useState<boolean>(false);
  const [current, setCurrent] = useState<string[]>([]);
  const formRef = useRef<ProFormInstance>();

  const handleOpen = () => {
    setVisible(true);
  };

  const handleClose = () => {
    setVisible(false);
  };

  const unBind = () => {
    resetShunFun(queryData).then((res) => {
      const { code, msg } = res;
      if (code == 0) {
        message.success(msg);
        onComplete();
      } else {
        message.error(msg);
      }
    });
  };

  const handleChange = (mode: string) => {
    formRef.current?.resetFields(['brands', 'time']);
    if (mode === '1') {
      formRef.current?.setFieldsValue({ brands: undefined, time: undefined });
    } else {
      const _time = mode === '2' ? '180' : '50';
      formRef.current?.setFieldValue('time', _time);
    }
  };

  const onSubmit = async (config: any) => {
    const { code, msg } = await setShunFun({ ...queryData, config });
    if (code == 0) {
      message.success('操作成功');
      onComplete();
      setVisible(false);
      return true;
    } else {
      message.error(msg);
      return false;
    }
  };

  useEffect(() => {
    if (visible) {
      const { brands = [], type = '' } = record;
      setCurrent(brands);
      formRef.current?.setFieldsValue({
        ...record,
        type: `${type}`,
      });
    }
  }, [visible, record]);
  return (
    <div>
      <>
        {record ? (
          <Space direction='horizontal'>
            <a onClick={handleOpen}>修改</a>
            <Popconfirm
              title={
                <div
                  dangerouslySetInnerHTML={{
                    __html: `解除关系后为普通${roleName}，<br />确认解除该顺丰独占账号？`,
                  }}
                ></div>
              }
              style={{ width: 150 }}
              onConfirm={unBind}
            >
              <a>解除关系</a>
            </Popconfirm>
          </Space>
        ) : (
          <a onClick={handleOpen}>去配置</a>
        )}
      </>
      <DrawerForm
        title='配置顺丰独占账号'
        width={winSize === 'xs' ? 400 : 700}
        formRef={formRef}
        onFinish={onSubmit}
        visible={visible}
        layout='horizontal'
        drawerProps={{
          destroyOnClose: true,
          onClose: handleClose,
        }}
        {...layoutCol}
      >
        <ProFormSelect
          label='模式'
          name='type'
          valueEnum={mode_name}
          debounceTime={300}
          allowClear={false}
          fieldProps={{
            placeholder: '请选择模式',
            onChange: handleChange,
          }}
        />
        <ProFormDependency name={['type']}>
          {({ type }) => {
            const hidden = !type || type == '1';
            return (
              <>
                <ProForm.Item hidden={hidden} wrapperCol={{ span: 24 }}>
                  <ProFormCheckbox.Group
                    label='选择运力'
                    name='brands'
                    request={getBrandList}
                    fieldProps={{
                      onChange: (event: any) => {
                        setCurrent(event);
                      },
                    }}
                    params={{
                      formatResponse: (data: OptionsType[]) =>
                        data
                          .filter((item) => item.value !== 'sftc')
                          .map((item) => ({
                            ...item,
                            disabled:
                              (type == 2 &&
                                current.length === 1 &&
                                !current.includes(item.value)) ||
                              item.value === 'sftc',
                          })),
                    }}
                    {...layoutCol}
                  />
                  <ProFormDigit
                    label='顺丰优先发单时间'
                    name='time'
                    rules={hidden ? [] : [{ required: true, message: '请输入顺丰优先发单时间' }]}
                    fieldProps={{
                      placeholder: '请输入顺丰优先发单时间',
                      precision: 0,
                    }}
                    min={0}
                    max={300}
                    {...layoutCol}
                    addonAfter='s'
                  />
                </ProForm.Item>
              </>
            );
          }}
        </ProFormDependency>
      </DrawerForm>
    </div>
  );
};

export default KbSfDrawer;
